import React, { createContext, useContext, useReducer } from "react";

// 这里只是定义个context容器，不用传递数据参数
const ContainerContext = createContext();
const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case "increment":
      return { count: state.count + 1 };
    case "decrement":
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  // 这里使用context
  const { state, dispatch } = useContext(ContainerContext);
  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
    </>
  );
}

function Tip() {
  console.log("tip");
  return <span>计数器</span>;
}

function Container(props) {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <ContainerContext.Provider value={{ state, dispatch }}>
      {/* <Tip />
      <Counter /> */}
      {props.children}
    </ContainerContext.Provider>
  );
}
function App() {
  return (
    <Container>
      <Tip />
      <Counter />
    </Container>
  );
}

export default App;
